<template>
  <div>

    <div>
      <a-form :form="form">
        <a-row>
          <a-col :span="12">
            <a-form-item label="一级分类" v-bind="formItemLayout">
              <a-select
                v-decorator="[
                  'firId',
                  { rules: [{ required: true, message: '请选择一级分类' }] },
                ]"
                placeholder="请选择一级分类"
                @change="refreshSecId"
              >
                <a-select-option v-for="item in firTypeList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="二级分类" v-bind="formItemLayout">
              <a-select
                v-decorator="[
                  'secId',
                  { rules: [{ required: true, message: `请选择${form.getFieldValue('firId') ? '二级' : '一级'}分类` }]},
                ]"
                :disabled="!form.getFieldValue('firId')"
                :placeholder="`请选择${form.getFieldValue('firId') ? '二级' : '一级'}分类`"
              >
                <a-select-option
                  v-for="item in ($get(itemSecTypeListMaps, form.getFieldValue('firId'), []))"
                  :key="item.id"
                  :value="item.id"
                >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="物资名称" v-bind="formItemLayout">
              <span v-if="disabledKeys.includes('name')">{{ itemData.name }}</span>
              <a-input
                v-decorator="[
                  'name',
                  { rules: [{ required: true, message: '请输入', whitespace: true, type: 'string' }] },
                ]"
                :hidden="disabledKeys.includes('name')"
                placeholder="请输入"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="物资类型" v-bind="formItemLayout">
              <a-radio-group
                v-decorator="[
                  'type',
                  { rules: [{ required: true, type: 'number', message: '请选择物资类型' }], initialValue: 1 },
                ]"
                :options="[{ value: 1, label: '固定资产' }, { value: 2, label: '非固定资产' }]"
                placeholder="请选择物资类型"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="规格型号" v-bind="formItemLayout">
              <a-input
                v-decorator="[
                  'model',
                  { rules: [{ message: '请输入', type: 'string', whitespace: true }] },
                ]"
                placeholder="请输入"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="物品单位" v-bind="formItemLayout">
              <a-input
                v-decorator="[
                  'unit',
                  { rules: [{ message: '请输入', type: 'string', whitespace: true }] },
                ]"
                placeholder="请输入"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="总库存量" v-bind="formItemLayout">
              <span v-if="disabledKeys.includes('quantity')">{{ itemData.quantity }}</span>
              <a-input-number
                v-decorator="[
                  'quantity',
                  { rules: [{ type: 'number', message: '请输入' }], initialValue: 0 },
                ]"
                :hidden="disabledKeys.includes('quantity')"
                class="width-fix"
                :min="0"
                :max="10000000000000000"
                placeholder="请输入"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="有效日期" v-bind="formItemLayout">
              <CalendarPicker :visible="showPicker" :default-dates="defaultDates" @ok="handleOk" @cancel="showPicker = false" />
              <a-input
                v-decorator="[
                  'effectiveTime',
                  { rules: [{ message: '请选择' }] },
                ]"
                placeholder="请选择"
                read-only
                @click="pickDates"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="物品图片" v-bind="formItemLayout">
              <a-upload
                accept="image/*"
                list-type="picture-card"
                :show-upload-list="false"
                :before-upload="beforeUpload"
                :custom-request="handleUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" style="width: 100%" alt="">
                <div v-else>
                  <a-icon :type="sending ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>

      </a-form>
    </div>

    <div>
      <span class="success-link" @click="handleAdd">新增物品记录</span>
      <a-table
        :columns="columns"
        :data-source="list"
        :locale="{ emptyText: '未新增物品记录' }"
        :pagination="false"
        row-key="id"
      >
        <!-- 部门 -->
        <template slot="deptId" slot-scope="item">
          <a-select
            v-show="item.editable"
            v-model="item.deptId"
            show-search
            placeholder="请选择调用区域"
            style="width: 100%"
          >
            <a-select-option
              v-for="dItem in deptList"
              :key="dItem.deptId"
              :value="dItem.deptId"
            >{{ dItem.deptName }}</a-select-option>
          </a-select>
          <span v-show="!item.editable">{{ $get(deptMaps, `${item.deptId}.deptName`, '无') }}</span>
        </template>
        <!-- 区域 -->
        <template slot="areaId" slot-scope="text,item">
          <a-cascader
            v-show="item.editable"
            v-model="item.areaId"
            :disabled="!item.deptId"
            not-found-content="没有数据"
            :options="$get(deptListMaps, item.deptId, [])"
            :display-render="({ labels }) => labels.join(' > ')"
            :field-names="{ label: 'name', value: 'id', children: 'children' }"
            :placeholder="item.deptId ? '请选择区域' : '请选择部门'"
            style="width: 100%"
          />
          <span v-show="!item.editable">{{
            $get(item, 'areaId.length') ? $get(areaMaps, `${item.areaId[item.areaId.length - 1]}.name`, '无') : '无'
          }}</span>
        </template>
        <!-- 负责人 -->
        <template slot="userId" slot-scope="text,item">
          <span
            v-if="$get(item, 'areaId.length')"
            style="cursor: default"
          >{{ $get(areaMaps, `${item.areaId[item.areaId.length - 1]}.userName`, '请切换区域') }}</span>
          <span v-else>请选择区域</span>
        </template>
        <template slot="quantity" slot-scope="text,item">
          <a-input-number
            v-show="item.editable"
            v-model="item.quantity"
            class="width-fix"
            :min="0"
            :max="10000000000000000"
            placeholder="请输入"
          />
          <span v-show="!item.editable">{{ text || '0' }}</span>
        </template>
        <template slot="action" slot-scope="text,item">
          <div class="action-container start">
            <span v-show="item.editable" class="success-link" @click="handleSave(item)">保存</span>
            <span v-show="!item.editable" class="primary-link" @click="handleEdit(item)">编辑</span>
            <span class="primary-link" @click="handleDel(item)">删除</span>
          </div>
        </template>
      </a-table>
    </div>

    <div v-if="showButton" class="button-container">
      <a-button :loading="sending" class="success-btn" @click="handleSubmit">确定</a-button>
      <a-button class="danger-btn-border" @click="$emit('cancel')">取消</a-button>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { CalendarPicker } from '@/components'
import { uuid } from '@/utils/util'

export default {
  name: 'AddItem',
  components: { CalendarPicker },
  props: {
    formItemLayout: {
      type: Object,
      required: true,
      default: _ => ({})
    },
    itemData: {
      type: Object,
      default: _ => ({})
    },
    sending: {
      type: Boolean,
      default: false
    },
    showButton: {
      type: Boolean,
      default: false
    },
    disabledKeys: {
      type: Array,
      default: () => []
    }
  },

  data () {
    return {
      showPicker: false,
      defaultDates: [],

      form: this.$form.createForm(this),

      previewImage: '',
      imageUrl: '',

      columns: [
        { title: '负责部门', width: '20%', scopedSlots: { customRender: 'deptId' }},
        { title: '调用区域', width: '20%', scopedSlots: { customRender: 'areaId' }},
        { title: '负责人', width: '20%', dataIndex: 'userId', scopedSlots: { customRender: 'userId' }},
        { title: '新增数量', width: '20%', dataIndex: 'quantity', scopedSlots: { customRender: 'quantity' }},
        { title: '操作', width: '20%', scopedSlots: { customRender: 'action' }}
      ],
      list: []
    }
  },

  computed: {
    ...mapState({
      firTypeList: state => state.property.itemFirTypeList,
      itemSecTypeListMaps: state => state.property.itemSecTypeListMaps,
      deptList: state => state.basic.deptList,
      deptMaps: state => state.basic.deptMaps,
      deptListMaps: state => state.basic.deptListMaps,
      areaMaps: state => state.basic.areaMaps
    }),
    totalQty () {
      let count = 0
      this.list.forEach(i => (count += i.quantity / 1))
      return count
    }
  },

  watch: {
    list (arr) {
      arr.forEach((i, k) => Object.assign(i, { index: k + 1 }))
    },

    itemData: {
      handler (obj) {
        const { defaultDates } = this
        const { effectiveTime = '', images } = obj
        const keys = ['firId', 'secId', 'name', 'type', 'model', 'unit', 'quantity', 'effectiveTime']
        const data = {}
        keys.forEach(key => { if (obj[key] && obj[key] !== '暂无') data[key] = obj[key] })
        this.$nextTick(_ => {
          if (effectiveTime) {
            defaultDates.splice(0, defaultDates.length, ...effectiveTime.split(',').filter(i => i))
          }
          if (images) this.imageUrl = images
          this.form.setFieldsValue(data)
        })
      },
      immediate: true
    }
  },

  mounted () {
    const { getTempData, list } = this
    const tempList = getTempData() || []
    list.push(...tempList)
  },

  methods: {
    handleSubmit () {
      const { $message, imageUrl, list, totalQty, form, areaMaps, $get } = this
      const self = this
      form.validateFieldsAndScroll({ scroll: { offsetTop: 100 }}, (err, values) => {
        if (err) return false
        const someEmpty = list.some(item => ['areaId', 'deptId', 'quantity'].some(k => !item[k]))
        $message.destroy()
        if (someEmpty) return $message.error('物品记录列表中，数据不能为空')
        if (totalQty > values.quantity) return $message.error('新增数量总和不能比库存总量多')

        const data = { ...values, images: imageUrl }
        data.assetsGoodsDetailFormList = list.map(({ areaId, deptId, quantity }) => {
          areaId = areaId[areaId.length - 1]
          const userId = $get(areaMaps, `${areaId}.userId`)
          return { areaId, deptId, quantity, userId }
        })
        data.quantity -= totalQty
        if (data.quantity < 0) data.quantity = 0

        self.$emit('submit', data)
      })
    },

    refreshSecId () {
      this.form.setFieldsValue({ secId: undefined })
    },

    handleOk (effectiveTime = []) {
      effectiveTime = effectiveTime.join(',')
      this.showPicker = false
      this.form.setFieldsValue({ effectiveTime })
    },

    pickDates () {
      const { form, defaultDates } = this
      const dates = form.getFieldValue('effectiveTime')
      if (dates) defaultDates.splice(0, defaultDates.length, ...dates.split(','))
      this.showPicker = true
    },

    getTempData () {
      if (!process.client) return {}
      return JSON.parse(sessionStorage.getItem('temp_new_item_record') || '[]')
    },

    handleEdit (item) {
      Object.assign(item, { editable: true })
    },

    handleSave (item) {
      Object.assign(item, { editable: false })
      if (process.client) {
        const tempList = this.getTempData() || []
        const index = this.$findindex(tempList, i => i.id === item.id)
        if (index > -1) tempList.splice(index, 1, item)
        else tempList.push(item)
        tempList.sort((a, b) => a.index - b.index)
        sessionStorage.setItem('temp_new_item_record', JSON.stringify(tempList))
      }
    },

    handleDel (item) {
      const tempList = this.getTempData() || []
      const index = this.$findindex(tempList, i => i.id === item.id)
      if (index > -1) {
        tempList.splice(index, 1)
        sessionStorage.setItem('temp_new_item_record', JSON.stringify(tempList))
      }
      this.list.splice(item.index - 1, 1)
    },

    handleAdd () {
      this.list.push({ id: uuid(), areaId: undefined, classId: undefined, userId: undefined, quantity: undefined, editable: false })
    },

    /**
     * 上传图片
     */
    async handleUpload ({ file, onError, onSuccess }) {
      const { $message } = this
      if (!file) return $message.error('无法上传')

      this.$emit('sendingChange', 1)
      const token = await this.$getQinuiToken()
      if (!token) {
        $message.destroy()
        $message.error('请稍后再试')
        this.$emit('sendingChange')
      }

      const url = await this.$uploadImage(token, { file, onError, onSuccess })
      if (url) this.imageUrl = url
      this.$emit('sendingChange')
    },

    beforeUpload (file) {
      // const isJPG = file.type === 'image/jpeg'
      // if (!isJPG) {
      //   this.$message.error('You can only upload JPG file!')
      // }
      const isJPG = true
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJPG && isLt2M
    }
  }

}
</script>

<style lang="less" scoped>
  .width-fix {
    width: 100%;
  }

  .button-container {
    text-align: center;
    margin-top: 20px;
  }
</style>
